/*
 * CustomerDAO.java
 *
 * Created on February 18, 2007, 8:31 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package edu.byu.isys413.samlam;

import java.sql.*;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author Sam
 */
public class CustomerDAO {
    ///////////////////////////////////////
    ///   Singleton pattern
    
    private static CustomerDAO instance;
    
    /** Creates a new instance of CustomerDAO */
    private CustomerDAO() {
    }

    
    
    public static synchronized CustomerDAO getInstance() {
        if (instance == null) {
            instance = new CustomerDAO();
        }
        return instance;
    }
    
    /////////////////////////////////
    ///   CREATE
    
    /**
     * There's no need for two creates because we don't need
     * a connection to create BOs.  We run the insert statement
     * later, when it get's saved for the first time.
     */
    public Customer create() {
        Customer c = null;
        try{
            String id = GUID.generate();
            c = new Customer(id);
            Cache cache = Cache.getInstance();
            cache.put(c.getId(), c);
            
        }catch(Exception e){
            e.printStackTrace();
        }
        return c;
    }
    
    
    /////////////////////////////////////
    ///   READ
    
    /**
     * This is the public read statement.  It loads an existing record
     * from the database.
     */
    public synchronized Customer read(String id) throws DataException {
        // check to see if id in the cache
        Customer c = (Customer)Cache.getInstance().get(id);
        if(c != null){
            // if so, return it immediately
            return c;
        }
        
        
        
        Connection conn = null;
        try {
            // retrieve a database connection from the pool
            conn = ConnectionPool.getInstance().get();
            // call read with a connection (the other read method in this class)
            c = CustomerDAO.getInstance().read(id, conn);
            
            // release the connection
            conn.commit();
            ConnectionPool.getInstance().release(conn);
            
        }catch (ConnectionPoolException e4){
            throw new DataException("Could not get a connection to the database.");
            
        }catch (SQLException e) {
            // rollback
            try{
                conn.rollback();
                ConnectionPool.getInstance().release(conn);
            }catch(SQLException e2){
                throw new DataException("Big error: could not even release the connection", e2);
            }catch (ConnectionPoolException e3){
                throw new DataException("Could not get a connection to the database.");
                
            }
            throw new DataException("Could not retrieve record for id=" + id, e);
        }
        
        // return object
        return c;
    }
    
    /**
     *  This is a package method that is called by the public read (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     */
    synchronized Customer read(String id, Connection conn) throws SQLException, DataException {
        // check again if the id is in the cache, and if so,
        // just get it from the cache.  we need to check again
        // because this method might be called directly from
        // another DAO rather than from read above.
        Customer customer = (Customer)Cache.getInstance().get(id);
        if(customer != null){
            return customer;
        }
        // if not in the cache, get a result set from
        // a SELECT * FROM table WHERE id=guid
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM customer WHERE customer_id = '"+ id + "'");
        
        //create a prepared statement
        //query the database
        //call sets from the result set
        Customer c;
        String memberId=null;
        if (rs.next()) {
            c = new Customer(rs.getString("customer_id"));
            
            c.setCity(rs.getString("city"));
            c.setFirstName(rs.getString("first_name"));
            c.setLastName(rs.getString("last_name"));
            c.setEmail(rs.getString("email"));
            c.setAddress(rs.getString("street"));
            c.setCity(rs.getString("city"));
            c.setState(rs.getString("state"));
            c.setZipCode(rs.getString("zip"));
            c.setPhone(rs.getString("phone"));
            
            // get any subobjects (for example, if this was the CustomerDAO,
            // we'd need to call the MembershipDAO to load the membership record.
            if(c.getMember()==null){
                Member m = MemberDAO.getInstance().readByCustomer(c.getId(), conn);
                c.setMember(m);
            }
            
            c.setObjectAlreadyInDB(true);
            
            
            // save to the cache
            
            Cache.getInstance().put(c.getId(), c);
            stmt.close();
        }else{
            throw new DataException("Object was not found in the database.");
            
        }
        // return the BO
        return c;
    }
    
    //////////////////////////////////
    ///   UPDATE
    
    /**
     * This is the public save method.  It is what is called when
     * the user (controller) code wants to save or update an object
     * into the database.
     */
    public synchronized void save(Customer customer) throws DataException {
        Connection conn = null;
        try {
            // retrieve a database connection from the pool
            conn = ConnectionPool.getInstance().get();
            // call save with a connection (the other save method in this class)
            this.save(customer, conn);
            // release the connection
            conn.commit();
            ConnectionPool.getInstance().release(conn);
        }catch (ConnectionPoolException e4){
            throw new DataException("Could not get a connection to the database.");
        }catch (SQLException e) {
            // rollback
            try {
                conn.rollback();
                ConnectionPool.getInstance().release(conn);
            }catch (ConnectionPoolException e4){
                throw new DataException("Could not get a connection to the database.");
            }catch (SQLException e2) {
                throw new DataException("Big error: could not even release the connection", e2);
            }
            
            throw new DataException("Could not retrieve record for id=" + customer.getId(), e);
        }
    }
    
    
    /**
     *  This is a package method that is called by the public save (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     *
     *  By having other DAOs call this save method (rather than update or
     *  insert below, each DAO in a chained save (like the CustomerDAO calling
     *  MembershipDAO calling InterestDAO save chain) can independently decide
     *  whether to udpate or insert the BO it's saving.  That's why I made
     *  update and insert private rather than package level -- if you call
     *  them directly from another DAO, this DAO can't decide whether it's
     *  object needs to be inserted or updated.
     */
    synchronized void save(Customer customer, Connection conn) throws SQLException, DataException {
        // check the dirty flag in the object.  if it is dirty,
        // run update or insert
        if (customer.isDirty()) {
            
            if (customer.isObjectAlreadyInDB() == true) {
                update(customer, conn);
            }else{
                insert(customer, conn);
            }
            // set the dirty flag to false now that we've saved it
            customer.setDirty(false);
            
        }
        
        // call save(bo, conn) on any subobjects (like CustomerDAO to MembershipDAO)
        if(customer.getMember() != null){
            MemberDAO.getInstance().save(customer.getMember(), conn);
        }
        // touch the cache for the object
        Cache.getInstance().touch(customer.getId());
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL udpate statement and make it more readable.  But
     * logically, it's really just a part of save.
     */
    private synchronized void update(Customer customer, Connection conn) throws SQLException, DataException {
        // do the update statement
        Statement stmt = conn.createStatement();
        stmt.executeUpdate("UPDATE customer set customer_id='"+customer.getId()+"', first_name='"+customer.getFirstName()+"', last_name='"+customer.getLastName()+"', email='"+customer.getEmail()+"', street='"+customer.getAddress()+"', city='"+customer.getCity()+"', state='"+customer.getState()+"', zip='"+customer.getZipCode()+"', phone='"+customer.getPhone()+"' WHERE customer_id='"+customer.getId()+"'");
        stmt.close();
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL insert statement and make it more readable.  But
     * logically, it's really just a part of save.
     */
    private synchronized void insert(Customer customer, Connection conn) throws SQLException, DataException {
        // do the insert SQL statement
        Statement stmt = conn.createStatement();
        stmt.executeUpdate("INSERT INTO customer VALUES ('"+customer.getId()+"', '"+customer.getFirstName()+"', '"+customer.getLastName()+"','"+customer.getEmail()+"', '"+customer.getAddress()+"', '"+customer.getCity()+"', '"+customer.getState()+"', '"+customer.getZipCode()+"',  '"+customer.getPhone()+"')");
        stmt.close();
        // tell the object that it's now in the db (so we call update next time not insert)
        customer.setObjectAlreadyInDB(true);
    }
    
    
    ////////////////////////////////////
    ///   DELETE
    // we are not supporting because we never want to delete the customer from
    // our database.
    
    
    
    //////////////////////////////
    ///  SEARCH methods
    
    public List<Object[]> getAll() throws DataException {
        LinkedList<Object[]> allList = new LinkedList();
        // get the connection
        
        Connection conn = null;
        try{
            
            conn = ConnectionPool.getInstance().get();
            
            // sql the names, phone, and ids
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT customer_id, first_name, last_name, phone FROM customer");
            
            // while loop to populate the list from the results
            while(rs.next()) {
                String[] jimmy = {rs.getString("first_name"), rs.getString("last_name"), rs.getString("phone"), rs.getString("customer_id")};
                allList.add(jimmy);
            }
            stmt.close();
            // release my connection
            ConnectionPool.getInstance().release(conn);
            // return the list
            return allList;
        }catch (ConnectionPoolException e4){
            throw new DataException("Could not get a connection to the database.");
        }catch (SQLException e) {
            // rollback
            try {
                conn.rollback();
                ConnectionPool.getInstance().release(conn);
            }catch (ConnectionPoolException e4){
                throw new DataException("Could not get a connection to the database.");
            }catch (SQLException e2) {
                throw new DataException("Big error: could not even release the connection", e2);
            }
            
            throw new DataException("Could not retrieve any customer records", e);
        }
        
    }
    
    public List<Customer> getByName(String fname, String lname) throws DataException {
        List<Customer> custList = new LinkedList();
        // get the connection
        
        Connection conn = null;
        try{
            
            conn = ConnectionPool.getInstance().get();
            
            // sql the customer
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT customer_id FROM customer WHERE '"+fname+"'=first_name AND '"+lname+"'=last_name");
            
            // while loop to populate the list from the results
            while(rs.next()) {
                String custId = rs.getString("customer_id");
                Customer customer = this.read(custId, conn);
                custList.add(customer);
            }
            stmt.close();
            // release my connection
            ConnectionPool.getInstance().release(conn);
            // return the list
            return custList;
        }catch (ConnectionPoolException e4){
            throw new DataException("Could not get a connection to the database.");
        }catch (SQLException e) {
            // rollback
            try {
                conn.rollback();
                ConnectionPool.getInstance().release(conn);
            }catch (ConnectionPoolException e4){
                throw new DataException("Could not get a connection to the database.");
            }catch (SQLException e2) {
                throw new DataException("Big error: could not even release the connection", e2);
            }
            
            throw new DataException("Could not retrieve any customer records", e);
        }
        
    }
    
    public List<Customer> getByPhone(String phoneNumber) throws DataException {
        LinkedList<Customer> custList = null;
        // get the connection
        
        Connection conn = null;
        try{
            
            conn = ConnectionPool.getInstance().get();
            
            // sql the customer using phoneNumber
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT customer_Id FROM customer WHERE '"+phoneNumber+"'= phone");
            
            // while loop to populate the list from the results
            while(rs.next()) {
                String custId = rs.getString("customerid");
                Customer customer = this.read(custId, conn);
                custList.add(customer);
            }
            // release my connection
            stmt.close();
            ConnectionPool.getInstance().release(conn);
            // return the list
            return custList;
        }catch (ConnectionPoolException e4){
            throw new DataException("Could not get a connection to the database.");
        }catch (SQLException e) {
            // rollback
            try {
                conn.rollback();
                ConnectionPool.getInstance().release(conn);
            }catch (ConnectionPoolException e4){
                throw new DataException("Could not get a connection to the database.");
            }catch (SQLException e2) {
                throw new DataException("Big error: could not even release the connection", e2);
            }
            
            throw new DataException("Could not retrieve any customer records", e);
        }
        
    }
    
}
